﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;

namespace Pavilion.DesignerTool
{
    /// <summary>
    /// Interaction logic for ColorGrid.xaml
    /// </summary>
    public partial class ColorGrid : UserControl
    {
        private ColorGridModel _viewModel;
        public event Action<Color> SelectedColorChanged;

        public ColorGrid()
        {
            InitializeComponent();

            ViewModel = new ColorGridModel();
            ViewModel.SelectedColorChanged += (SolidColorBrush selectedColor) => OnSelectedColorChanged(selectedColor.Color);
        }

        private void OnSelectedColorChanged(Color selectedColor)
        {
            if (SelectedColorChanged != null)
                SelectedColorChanged(selectedColor);
        }

        private bool isLoaded;
        private void ColorGrid_Loaded(object sender, RoutedEventArgs e)
        {
            if (isLoaded)
                return;

            if (!DesignerProperties.GetIsInDesignMode(this))
            {
                ViewModel.RenderHueDisplay();
                ViewModel.RenderColorGrid();
            }

            isLoaded = true;
        }

        private void MoveSelectorOnCanvas(Canvas canvas)
        {
            if (Mouse.LeftButton == MouseButtonState.Released)
                return;

            if (canvas == colorGridCanvas)
                ViewModel.ColorSelectorPosition = Mouse.GetPosition(colorGridCanvas);
            else
                ViewModel.HueAmount = (float)Mouse.GetPosition(hueGridCanvas).Y;
        }

        public ColorGridModel ViewModel
        {
            get { return _viewModel; }
            set { _viewModel = value; this.DataContext = _viewModel; }
        }

        private void Canvas_MouseMove(object sender, MouseEventArgs e)
        {
            MoveSelectorOnCanvas((Canvas)sender);
        }

        private void Canvas_MouseDown(object sender, MouseButtonEventArgs e)
        {
            MoveSelectorOnCanvas((Canvas)sender);
        }

        private void Canvas_MouseLeave(object sender, MouseEventArgs e)
        {
            MoveSelectorOnCanvas((Canvas)sender);
        }
    }
}
